<template>
  <div class="container">
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
      <el-form-item label="商品分类" prop="category" align="left">
        <el-select v-model="ruleForm.category" placeholder="请选择商品分类">
          <el-option v-for="item in categorys"
                     :key="item._id"
                     :label="item.name"
                     :value="item.name"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="商品名称" prop="name" align="left">
        <el-input v-model="ruleForm.name"></el-input>
      </el-form-item>
      <el-form-item label="商品价格" prop="price" align="left">
        <el-input v-model="ruleForm.price">
          <span slot="append">元</span>
        </el-input>
      </el-form-item>
      <el-form-item label="商品数量" prop="num" align="left">
        <el-input-number v-model="ruleForm.num" @change="handleChange" :min="1" :max="10"
                         label="描述文字"></el-input-number>
      </el-form-item>
      <el-form-item label="是否在售" prop="isSale" align="left">
        <el-switch
            v-model="ruleForm.isSale=='true'"
            active-color="#13ce66"
            inactive-color="#ff4949"
            active-text="true"
            inactive-text="false">
          >
        </el-switch>
      </el-form-item>
      <el-form-item label="商品描述" prop="desc" align="left">
        <el-input type="textarea" v-model="ruleForm.desc"></el-input>
      </el-form-item>
      <el-form-item label="商品图片" prop="imgs" align="left">
        <el-upload
            class="upload-demo"
            action="http://localhost:7000/file/upload"
            :on-success="handleSuccess"
            :on-remove="handleRemove"
            :file-list="fileList"
            list-type="picture">
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
        </el-upload>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
export default {
  data() {
    var validateImgs = (rule, value, callback) => {
      if (value.length < 1) {
        return callback(new Error('至少上传一张图片'));
      } else {
        callback();
      }
    }
    return {
      fileList: [],
      categorys: [],
      ruleForm: {
        name: '',
        price: 0.0,
        num: 0,
        isSale: 'false',
        desc: '',
        imgs: [],
        category: ''
      },
      action: '',
      rules: {
        name: [
          {required: true, message: '请输入商品名称', trigger: 'blur'},
          {min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur'}
        ],
        price: [
          {required: true, message: '请输入单品价格', trigger: 'blur'},
          {pattern: /^(?!(0[0-9]{0,}$))[0-9]{1,}[.]{0,}[0-9]{0,}$/, message: '价格必须为大于0的数！', trigger: 'blur'}
        ],
        num: [
          {required: true, message: '请选择商品库存量', trigger: 'blur'}
        ],
        isSale: [
          {required: true, message: '请选择是否在售', trigger: 'change'}
        ],
        imgs: [
          {validator: validateImgs, trigger: 'null'}
        ],
        category: [
          {required: true, message: '请选择商品分类', trigger: 'change'}
        ],
      }
    };
  },
  created() {
    this.getCategoryAll()
    const {info, action} = this.$route.query
    if (action && action == 'edit') {
      this.action = 'edit'
      if (info) {
        this.ruleForm = JSON.parse(info)
        for (let i = 0; i < this.ruleForm.imgs.length; i++) {
          this.fileList.push({
            name: this.ruleForm.name + i + '.jpg',
            url: 'http://localhost:7000/file/download?filename=' + this.ruleForm.imgs[i],
            response:{data: this.ruleForm.imgs[i], status: 'success'}
          })
        }
        // this.$message.warning("修改商品您需要重新上传图片")
      }
      // console.log(this.ruleForm)
    } else {
      this.action = 'add'
    }
  },
  methods: {

    //获取商品所有分类
    async getCategoryAll() {
      const result = await this.$http.get("/category/all")
      if (result.data.status == "success") {
        this.categorys = result.data.data
      } else {
        this.$message.error("获取商品类别失败...")
      }
    },
    //图片上传组件
    handleRemove(file, fileList) {
      console.log(fileList)
      this.fileList = fileList;
      //占位用于表单校验
      this.ruleForm.imgs.pop()
      this.$http.get(`file/delete? filename=${file.response.data}`)
    },
    //上传成功回调
    handleSuccess(response, file, fileList) {
      console.log(fileList)
      //占位用于表单校验
      this.ruleForm.imgs.push(0)
      this.fileList = fileList;
      console.log(this.fileList)
    },
    //改变商品数量
    handleChange(value) {
      console.log(value);
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$confirm(`您确定保存该操作吗?`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(async () => {
            // 确定操作
            if (this.action == 'add') {
              this.ruleForm.imgs = []
              //将需要上传的图片放入表单
              while (this.fileList.length > 0) {
                this.ruleForm.imgs.push(this.fileList.pop().response.data)
              }
              const result = await this.$http.post("goods/add", this.ruleForm)
              if (result.data.status == 'success') {
                this.$message.success("添加成功,可以继续添加...")
                this.ruleForm = {
                  name: '',
                  price: 0,
                  num: 0,
                  isSale: false,
                  desc: '',
                  imgs: [],
                  category: ''
                }
                this.fileList = []
              } else {
                this.$message.error("添加失败,请稍后重试...")
                this.$router.push('goodsEgit')
              }
            } else if (this.action == 'edit') {
              this.ruleForm.imgs = []
              //将需要上传的图片放入表单
              while (this.fileList.length > 0) {
                this.ruleForm.imgs.push(this.fileList.pop().response.data)
              }
              console.log(this.ruleForm.imgs)
              const result = await this.$http.put("goods/edit", this.ruleForm)
              if (result.data.status == 'success') {
                this.$message.success("修改成功")
              } else {
                this.$message.error("修改失败或没有修改,请稍后重试...")
              }
              this.$router.push('goods')
            }
          }).catch(() => {
            // 取消操作
            this.$message({
              type: 'info',
              message: '已取消'
            })
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    }
  }
}
</script>
<style scoped lang="scss">
.container {
  background-color: #fff;
  padding: 10px;

  .el-form {
    margin-top: 20px;
    width: 50%;
    /*  .el-select{
        display: flex;
      }
      .el-input-number{
        display: flex;
      }
      .el-switch{
        display: flex;
        margin-top: 10px;
      }*/
  }
}
</style>